<?php

namespace App\Console\Commands;

use App\Services\SwooleService;
use function foo\func;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class TestCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test_swoole';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'swoole服务';

    private $serv;


    private $_bind_id;
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->serv = new \Swoole\WebSocket\Server("0.0.0.0", 9501);
        $this->serv->on('Start', array($this, 'onStart'));
        $this->serv->on('Open', array($this, 'onOpen'));
        $this->serv->on('Message', array($this, 'onMessage'));
        $this->serv->on('Close', array($this, 'onClose'));
        $this->serv->start();
    }

    /**
     * 服务启动
     * @param $serv
     */
    public function onStart($serv)
    {
        echo "启动成功\n";
    }

    /**
     * 连接成功
     *
     */
    public function onOpen($serv, $request)
    {
        echo "【{$request->fd}】连接成功\n";
    }

    /**
     * 接收消息
     *
     */
    public function onMessage($serv, $frame)
    {
        echo "收到【{$frame->fd}】消息:{$frame->data}\n";
        $result = json_decode($frame->data, true);
        //关联用户
        if ($result['type'] == 'relate') {
            $this->_bind_id[$result['data']['id']][] = $frame->fd;
        } //发消息
        else if ($result['type'] == 'sendMessage') {
            if(isset($this->_bind_id[$result['data']['id']])){
                foreach ($this->_bind_id[$result['data']['id']] as $v) {
                    $serv->push($v, $frame->data);
                }
            }
        }

    }

    /**
     * 下线
     */
    public function onClose($serv, $fd)
    {
        echo "客户端【{$fd}】已下线\n";
    }

}
